package com.ziyun.erp.modules.supp.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cloud.bus.core.EventBusPusher;
import com.cloud.bus.event.goods.UpdateMerchantCacheEvent;
import com.service.utils.sms.SmsResponse;
import com.service.utils.sms.SmsUtils;
import com.utility.DateUtils;
import com.utility.StringUtils;
import com.ziyun.erp.common.e.DeleteEnum;
import com.ziyun.erp.common.e.supp.MerchantTypeEnum;
import com.ziyun.erp.common.e.supp.StateEnum;
import com.ziyun.erp.common.utils.HttpClientUtil;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.facilitator.entity.FacilitatorSellerRelationEntity;
import com.ziyun.erp.modules.facilitator.service.FacilitatorSellerRelationService;
import com.ziyun.erp.modules.freightages.service.SdbEctoolsRegionsService;
import com.ziyun.erp.modules.goods.service.GoodsService;
import com.ziyun.erp.modules.otherAccessory.entity.OtherAccessoryEntity;
import com.ziyun.erp.modules.otherAccessory.service.OtherAccessoryService;
import com.ziyun.erp.modules.supp.dao.SellerInfoDao;
import com.ziyun.erp.modules.supp.entity.*;
import com.ziyun.erp.modules.supp.service.*;
import com.ziyun.erp.modules.supp.utils.CompanyCheckUtils;
import com.ziyun.erp.modules.supp.utils.OcrUtils;
import com.ziyun.erp.modules.supp.vo.CompanySearchApiResult;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysUserEntity;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商户入驻接口实现
 * @author gaosheng
 * @email
 * @date 2018-07-27 11:26:47
 */
@Slf4j
@Service("sellerInfoService")
public class SellerInfoServiceImpl extends ServiceImpl<SellerInfoDao, SellerInfoEntity> implements SellerInfoService {

    @Value("${registerSellerInfoApi}")
    private String registerSellerInfoApi;

    @Value("${sellerCopyGoodsApi}")
    private String sellerCopyGoodsApi;

    @Autowired
    private OtherAccessoryService otherAccessoryService;
    @Autowired
    private SupplierRemarksService supplierRemarksService;
    @Autowired
    private SdbEctoolsRegionsService sdbEctoolsRegionsService;
    @Autowired
    private SellerSearchService sellerSearchService;
    @Autowired
    private SellerBusinessImageService sellerBusinessImageService;
    @Autowired
    private PopSysUserService popSysUserService;
    @Autowired
    private UserLoginCensusService userLoginCensusService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private FacilitatorSellerRelationService facilitatorSellerRelationService;

    @Override
    public R queryPageSellerInfoList(Map<String, Object> params) {
        int totalCount = this.baseMapper.countSellerInfo(params);
        int current = Integer.valueOf((String)params.get("page"));
        int size = Integer.valueOf((String)params.get("limit"));
        params.put("offset", (current - 1) * size);
        params.put("limit", size);
        List<SellerInfoEntity> list = this.baseMapper.queryPageSellerInfoList(params);

        // 查询省市区级联数据
        List<String> regions = sdbEctoolsRegionsService.queryRegionsSascade();
        // 审核人
        List<Map<String, String>> auditNames = this.baseMapper.querySuppliersAuditName();

        Map<String, Object> userDataMap = new HashMap<>();
        userDataMap.put("regions", JSONArray.fromObject(regions).toString());
        userDataMap.put("auditNames", auditNames);
        userDataMap.put("sellerTypeEnum", JsonUtils.enumToList(MerchantTypeEnum.class));

        R ok = R.ok();
        ok.put("page", new PageUtils(list, totalCount, size, current));
        ok.put("userData", userDataMap);
        return ok;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map setMainStore(Integer sellerId, Integer mainStoreId) {
        Map<String, Object> resultMap = new HashMap<>();
        SellerInfoEntity entity = this.baseMapper.selectById(sellerId);
        if (entity == null){
            resultMap.put("result", false);
            resultMap.put("msg", "未查询到商户信息！");
            return resultMap;
        }

        SellerInfoEntity mainEntity = this.baseMapper.selectById(mainStoreId);
        if (mainEntity == null){
            resultMap.put("result", false);
            resultMap.put("msg", "未查询到主店信息！");
            return resultMap;
        }

        // 本店设为主店
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("mainStoreId", 0);
        this.baseMapper.updateByMap(updateMap, sellerId);

        // 原主店设置为分店
        updateMap.put("mainStoreId", sellerId);
        this.baseMapper.updateByMap(updateMap, mainStoreId);

        // 原分店更换主店
        updateMap.put("sellerId", sellerId);
        updateMap.put("mainStoreId", mainStoreId);
        this.baseMapper.updateMainStore(updateMap);

        // 刷新微服务端缓存
        UpdateMerchantCacheEvent event = UpdateMerchantCacheEvent.builder().source(this).merchantId(Long.valueOf(sellerId)).build();
        EventBusPusher.syncPost(event);

        resultMap.put("result", true);
        resultMap.put("msg", "成功！");
        return resultMap;
    }

    @Override
    public SellerInfoEntity selectById(Integer sellerId) {
        return this.baseMapper.selectById(sellerId);
    }

    @Override
    public R audit(SellerInfoEntity sellerInfo, Long userId, String ipAddress) {
        Integer sellerId = sellerInfo.getSellerId();
        SellerInfoEntity entity = this.baseMapper.selectById(sellerId);
        if (entity == null){
            return R.error("未查询到商户信息！");
        }

        StringBuilder sb = new StringBuilder();
        String sellerState = sellerInfo.getSellerState();
        String overruleRemarks = sellerInfo.getOverruleRemarks();
        Map<String, Object> updateMap = new HashMap<>();
        if (StringUtils.equals(sellerState, StateEnum.IS_AUDITED.toCode())){
            String sellerName = entity.getSellerName();
            if (StringUtils.isBlank(sellerName)){
                return R.error("商户名不能为空!");
            }
            String sellerMobile = entity.getSellerMobile();
            if (StringUtils.isBlank(sellerMobile)){
                return R.error("手机号码不能为空!");
            }
            int count = this.baseMapper.selectCount(new EntityWrapper<>(new SellerInfoEntity())
                    .eq("seller_name", sellerName)
                    .eq("seller_state", StateEnum.IS_AUDITED.toCode())
                    .eq("disabled", DeleteEnum.NOT_DELETE.toInt())
            );
            if (count > 0){
                return R.error("审核失败，商户名已存在！");
            }
            Integer mainSellerId = entity.getMainSellerId();
            boolean validate = validateSellerMobile(sellerMobile, mainSellerId);
            if (!validate){
                return R.error("审核失败，手机号已注册！");
            }

            // 生成报价账号信息(包含报价平台买家会员账号信息)
            JSONObject param = new JSONObject();
            param.put("sellerId", sellerId);
            String result = HttpClientUtil.doPostJson(registerSellerInfoApi, param.toString());
            if (StringUtils.isBlank(result)){
                return R.error("调用接口服务失败！");
            }
            R resultMap = JsonUtils.getJsonToObject(result, R.class);
            int code = (int) resultMap.get("code");
            if (code != 0){
                String message = (String) resultMap.get("msg");
                return R.error(message);
            }

            // 20190115 取消商户注册同步商品业务
//            Boolean copyGoods = (Boolean) resultMap.get("copyGoods");
//            if (copyGoods != null && copyGoods){
//                sb.append("审核成功，初始化商品成功");
//            }else {
//                sb.append("审核成功，初始化商品失败");
//            }

            // 更新状态
            updateMap.put("overruleRemarks", overruleRemarks);
            updateMap.put("sellerState", sellerState);
            updateMap.put("auditName", userId.toString());
            updateMap.put("auditTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            this.baseMapper.updateByMap(updateMap, sellerId);

            // 查询是否代理商注册，更新审核状态
            FacilitatorSellerRelationEntity fsr = facilitatorSellerRelationService.selectOne(new EntityWrapper<>(new FacilitatorSellerRelationEntity())
                    .eq("seller_id", sellerId)
                    .ne("audit_status", 1)
                    .eq("disabled", DeleteEnum.NOT_DELETE.toInt())
            );
            if (fsr != null){
                Map<String, Object> facilitatorMap = new HashMap<>(1);
                facilitatorMap.put("auditStatus", 1);
                facilitatorSellerRelationService.updateByMap(facilitatorMap, fsr.getId());
            }

            // 发送短信
            JSONObject smsJson = new JSONObject();
            smsJson.put("name", entity.getName());
            smsJson.put("account", entity.getSellerName());
            SmsResponse smsResponse = null;
            String sellerType = entity.getSellerType();
            if ("0".equals(sellerType)){
                smsResponse = SmsUtils.sendMerchantEnter(sellerMobile, smsJson.toString());
            }else if ("1".equals(sellerType)){
                smsResponse = SmsUtils.sendFactoryEnter(sellerMobile, smsJson.toString());
            }
            if (StringUtils.equals(smsResponse.getCode(), "OK")) {
                sb.append("审核成功，短信已成功发送至用户！");
            } else {
                sb.append("审核成功，短信发送失败！");
            }
        }else if (StringUtils.equals(sellerState, StateEnum.NOT_PASS.toCode())){
            updateMap.put("sellerState", sellerState);
            updateMap.put("overruleRemarks", overruleRemarks);
            updateMap.put("auditName", userId.toString());
            updateMap.put("auditTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            this.baseMapper.updateByMap(updateMap, sellerId);
            sb.append("审核成功！");
        }else {
            return R.error("无效操作！");
        }

        // 刷新微服务端缓存
        UpdateMerchantCacheEvent event = UpdateMerchantCacheEvent.builder().source(this).merchantId(Long.valueOf(sellerId)).build();
        EventBusPusher.syncPost(event);

        return R.ok(sb.toString());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveImage(MerchantsImageVo merchantsImageVo) {
        Integer sellerId = merchantsImageVo.getSellerId();
        SellerInfoEntity entity = this.baseMapper.selectById(sellerId);

        // 插入图片信息
        OtherAccessoryEntity otherAccessory = merchantsImageVo.getOtherAccessory();
        otherAccessoryService.insert(otherAccessory);
        Integer accessoryId = otherAccessory.getId();
        Map<String, Object> updateMap = new HashMap<>();
        Integer imageType = merchantsImageVo.getImageType();
        switch (imageType){
            case 1: {
                // 删除原有门头照
                String logoUrl = entity.getLogoUrl();
                if (StringUtils.isNotBlank(logoUrl)){
                    updateMap.put("disabled", DeleteEnum.DELETE.toInt());
                    String[] split = logoUrl.split(",");
                    for (String url : split){
                        otherAccessoryService.updateByMap(updateMap, url);
                    }
                }
                updateMap.clear();
                updateMap.put("logoUrl", accessoryId);
            }break;
            case 2: {
                // 删除原有营业执照
                String businessUrl = entity.getBusinessUrl();
                if (StringUtils.isNotBlank(businessUrl)){
                    updateMap.put("disabled", DeleteEnum.DELETE.toInt());
                    String[] split = businessUrl.split(",");
                    for (String url : split){
                        otherAccessoryService.updateByMap(updateMap, url);
                    }
                }
                updateMap.clear();
                updateMap.put("businessUrl", accessoryId);
            }break;
            case 3:{
                // 更新原有商户图册
                String sellerImageUrl = entity.getSellerImageUrl();
                if (StringUtils.isNotBlank(sellerImageUrl)){
                    String[] split = sellerImageUrl.split(",");
                    List<String> list = new ArrayList<>(split.length);
                    list.addAll(Arrays.asList(split));
                    list.add(accessoryId.toString());
                    String join = StringUtils.join(list.toArray(), ",");
                    updateMap.put("sellerImageUrl", join);
                }else {
                    updateMap.put("sellerImageUrl", accessoryId);
                }
            } break;
            default: break;
        }

        this.baseMapper.updateByMap(updateMap, sellerId);

        // 刷新微服务端缓存
        UpdateMerchantCacheEvent event = UpdateMerchantCacheEvent.builder().source(this).merchantId(Long.valueOf(sellerId)).build();
        EventBusPusher.syncPost(event);

        return R.ok();
    }

    @Override
    public List<SellerInfoEntity> queryMainStore(Integer sellerId, Integer mainSellerId) {
        Map<String, Object> params = new HashMap<>();
        int mainId = mainSellerId;
        if (mainSellerId.intValue() == 0){
            mainId = sellerId;
        }
        params.put("mainSellerId", mainId);
        /*params.put("state", StateEnum.IS_AUDITED.toCode());*/
        params.put("disabled", DeleteEnum.NOT_DELETE.toInt());
        // 连锁店分店
        List<SellerInfoEntity> list = this.baseMapper.selectByMap(params);
        if (list.size() > 0){
            // 连锁店总店
            SellerInfoEntity entity = this.baseMapper.selectById(mainId);
            list.add(0, entity);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map saveRemark(Integer sellerId, String remarks) {
        Map<String, Object> resultMap = new HashMap<>();
        SellerInfoEntity entity = this.baseMapper.selectById(sellerId);
        if (entity == null){
            resultMap.put("result", false);
            resultMap.put("msg", "未查询到商户信息！");
            return resultMap;
        }

        SupplierRemarksEntity supplierRemarks = new SupplierRemarksEntity();
        String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
        supplierRemarks.setSrCreateName(username);
        supplierRemarks.setSrSupplierId(Long.valueOf(sellerId));
        supplierRemarks.setSrRemarks(remarks);
        supplierRemarksService.insert(supplierRemarks);

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("remarks", supplierRemarks.getSrRemarks());
        this.baseMapper.updateByMap(updateMap, sellerId);

        // 刷新微服务端缓存
//        UpdateMerchantCacheEvent event = UpdateMerchantCacheEvent.builder().source(this).merchantId(Long.valueOf(sellerId)).build();
//        EventBusPusher.syncPost(event);

        resultMap.put("result", true);
        resultMap.put("msg", "成功！");
        return resultMap;
    }

    @Override
    public Map updateView(Integer sellerId, String display) {
        Map<String, Object> resultMap = new HashMap<>();
        SellerInfoEntity entity = this.baseMapper.selectById(sellerId);
        if (entity == null){
            resultMap.put("result", false);
            resultMap.put("msg", "未查询到商户信息！");
            return resultMap;
        }

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("display", display);
        this.baseMapper.updateByMap(updateMap, sellerId);

        // 刷新微服务端缓存
        UpdateMerchantCacheEvent event = UpdateMerchantCacheEvent.builder().source(this).merchantId(Long.valueOf(sellerId)).build();
        EventBusPusher.syncPost(event);

        resultMap.put("result", true);
        resultMap.put("msg", "成功！");
        return resultMap;
    }

    @Override
    public Map addSalesman(SellerInfoEntity sellerInfo) {
        Map<String, Object> resultMap = new HashMap<>();

        Integer sellerId = sellerInfo.getSellerId();
        SellerInfoEntity entity = this.baseMapper.selectById(sellerId);
        if (entity == null){
            resultMap.put("result", false);
            resultMap.put("msg", "未查询到商户信息！");
            return resultMap;
        }

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("salesman", sellerInfo.getSalesman());
        updateMap.put("salesmanMobile", sellerInfo.getSalesmanMobile());
        this.baseMapper.updateByMap(updateMap, sellerId);

        // 刷新微服务端缓存
//        UpdateMerchantCacheEvent event = UpdateMerchantCacheEvent.builder().source(this).merchantId(Long.valueOf(sellerId)).build();
//        EventBusPusher.syncPost(event);

        resultMap.put("result", true);
        resultMap.put("msg", "成功！");
        return resultMap;
    }

    @Override
    public R sellerInfoValidity(Integer sellerId) {
        R result = R.ok();
        result.put("ocrBoolean", false);
        result.put("checkBoolean", false);
        SellerInfoEntity sellerInfo = this.baseMapper.selectById(sellerId);
        String sellerName = sellerInfo.getSellerName();
        String logoUrl = sellerInfo.getLogoUrl();
        if (StringUtils.isBlank(logoUrl)){
            return R.error("门头照未上传");
        }
        String businessUrl = sellerInfo.getBusinessUrl();
        if (StringUtils.isBlank(businessUrl)){
            return R.error("营业执照未上传");
        }
        String bUrl = businessUrl.split(",")[0];
        OtherAccessoryEntity otherAccessory = otherAccessoryService.selectById(bUrl);
        String imageUrl = otherAccessory.getImageUrl();
        com.alibaba.fastjson.JSONObject ocrResult = OcrUtils.imageOcr(sellerName, imageUrl);
        if (ocrResult != null) {
            boolean success = (boolean) ocrResult.get("success");
            if (success) {
                SellerBusinessImageEntity businessImage = new SellerBusinessImageEntity();
                businessImage.setName(ocrResult.get("name") == null ? "" : ocrResult.get("name").toString());
                businessImage.setType(ocrResult.get("type") == null ? "" : ocrResult.get("type").toString());
                businessImage.setPerson(ocrResult.get("person") == null ? "" : ocrResult.get("person").toString());
                businessImage.setEstablishDate(ocrResult.get("establish_date") == null ? "" : ocrResult.get("establish_date").toString());
                businessImage.setValidPeriod(ocrResult.get("valid_period") == null ? "" : ocrResult.get("valid_period").toString());
                businessImage.setAddress(ocrResult.get("address") == null ? "" : ocrResult.get("address").toString());
                businessImage.setCapital(ocrResult.get("capital") == null ? "" : ocrResult.get("capital").toString());
                businessImage.setBusiness(ocrResult.get("business") == null ? "" : ocrResult.get("business").toString());
                businessImage.setSuccess(ocrResult.get("success") == null ? "" : ocrResult.get("success").toString());
                businessImage.setResult(ocrResult.toJSONString());
                businessImage.setSbiType(Integer.valueOf(sellerInfo.getSellerType()));
                businessImage.setSupplierId(sellerId);
                businessImage.setSupplierName(sellerName);
                sellerBusinessImageService.insert(businessImage);

                result.put("ocrResult", ocrResult);
                String name = (String) ocrResult.get("name");
                if (StringUtils.equals(name, sellerName)) {
                    // 公司营业期限终止日期(例：证件上为"2014年04月16日至2034年04月15日"，算法返回"20340415")
                    // 当前算法将日期格式统一为输出为"年月日"(如"20391130"),并将"长期"表示为"29991231"，若证件上没有营业期限，则默认其为"长期",返回"29991231"。
                    String validPeriod = (String) ocrResult.get("valid_period");
                    if (!StringUtils.equals(validPeriod, "29991231")) {
                        try {
                            Date validPeriodDate = DateUtils.parseDate(validPeriod, new String[]{"yyyyMMdd"});
                            int compareTo = new Date().compareTo(validPeriodDate);
                            if (compareTo < 0) {
                                result.put("ocrBoolean", true);
                                result.put("ocrMessage", "营业执照识别成功");
                            } else {
                                result.put("ocrMessage", "营业执照识别已过期，请检查识别结果");
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }else {
                        result.put("ocrBoolean", true);
                        result.put("ocrMessage", "营业执照识别成功");
                    }
                } else {
                    result.put("ocrMessage", "营业执照识别名称与公司名称不符，请检查识别结果");
                }
            } else {
                result.put("ocrMessage", "营业执照无法识别，请联系后台管理员");
            }
        } else {
            result.put("ocrMessage", "调用识别服务失败，请联系后台管理员");
        }

        com.alibaba.fastjson.JSONObject checkResult = CompanyCheckUtils.companyCheck(sellerName);
        if (checkResult != null) {
            String status = (String) checkResult.get("Status");
            if (StringUtils.equals(status, "200")) {
                SellerSearchEntity sellerSearch = new SellerSearchEntity();
                sellerSearch.setSupplierId(sellerId);
                sellerSearch.setResult(checkResult.toJSONString());
                sellerSearch.setCreateName(UserUtils.getCurentUser().getUsername());
                sellerSearch.setQueryName(sellerName);
                String res = checkResult.get("Result").toString();
                List<CompanySearchApiResult> resList = (List<CompanySearchApiResult>) JsonUtils.queryJsonToList(res, CompanySearchApiResult.class);
                List<CompanySearchApiResult> collect = resList.stream().filter(item -> StringUtils.equals(item.getName(), sellerName)).collect(Collectors.toList());
                if (collect.size() > 0){
                    CompanySearchApiResult companySearchApiResult = collect.get(0);
                    sellerSearch.setName(companySearchApiResult.getName());
                    sellerSearch.setCreditCode(companySearchApiResult.getCreditCode());
                    sellerSearch.setNo(companySearchApiResult.getNo());
                    sellerSearch.setOperName(companySearchApiResult.getOperName());
                    sellerSearch.setStartDate(companySearchApiResult.getStartDate());
                    sellerSearch.setStatus(companySearchApiResult.getStatus());
                    result.put("checkBoolean", true);
                    result.put("checkResult", companySearchApiResult);
                    result.put("checkMessage", "企业工商数据验证成功");
                }else {
                    result.put("checkMessage", "未查询到企业 "+ sellerName +" 工商数据信息");
                }
                sellerSearchService.insert(sellerSearch);
            } else {
                result.put("checkMessage", "企业工商数据查询失败，请联系后台管理员");
            }
        } else {
            result.put("checkMessage", "调用工商数据查询服务失败，请联系后台管理员");
        }
        return result;
    }

    @Override
    public R updateInfo(SellerInfoEntity sellerInfo) {
        // 查询手机号是否更改, 手机号主店分店关系可以重复，不能与其他供应商手机号重复
        Integer sellerId = sellerInfo.getSellerId();
        SellerInfoEntity sellerInfoEntity = this.selectById(sellerId);
        String sellerMobile = sellerInfoEntity.getSellerMobile();
        String mobile = sellerInfo.getSellerMobile();
        if (!mobile.equals(sellerMobile)){
            Integer mainSellerId = sellerInfo.getMainSellerId();
            boolean result = validateSellerMobile(mobile, mainSellerId);
            if (!result){
                return R.error("手机号已注册");
            }
        }

        this.updateById(sellerInfo);

        // 刷新微服务端缓存
        UpdateMerchantCacheEvent event = UpdateMerchantCacheEvent.builder().source(this).merchantId(Long.valueOf(sellerInfo.getSellerId())).build();
        EventBusPusher.syncPost(event);

        return R.ok();
    }

    public boolean validateSellerMobile(String mobile, Integer mainSellerId){
        int selectCount = this.selectCount(new EntityWrapper<>(new SellerInfoEntity())
                .eq("seller_mobile", mobile)
                .eq("seller_state", "3")
                .eq("disabled", DeleteEnum.NOT_DELETE.toInt())
        );
        if (selectCount == 0){
            return true;
        }

        // 分店手机号可以和主店一样，但不能与其他供应商重复
        if (mainSellerId.intValue() > 0){
            SellerInfoEntity sellerInfo = this.selectById(mainSellerId);
            String sellerMobile = sellerInfo.getSellerMobile();
            if (mobile.equals(sellerMobile)){
                return true;
            }
        }

        return false;
    }

    @Override
    public List<SellerInfoEntity> queryFactoryList() {
        return this.baseMapper.queryFactoryList();
    }

    @Override
    public List<SellerInfoEntity> queryParam(Map<String, Object> params) {
        return this.selectByMap(params);
    }

    @Override
    public List<SellerInfoEntity> getSelectList() {
        return baseMapper.getSelectList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R removeSellerImage(Integer sellerId, Integer id) {
        SellerInfoEntity sellerInfo = this.selectById(sellerId);
        String sellerImageUrl = sellerInfo.getSellerImageUrl();
        String[] split = sellerImageUrl.split(",");
        List<String> list = new ArrayList<>(split.length);
        list.addAll(Arrays.asList(split));
        list.remove(id.toString());
        Map<String, Object> updateMap = new HashMap<>();
        if (list.size() == 0){
            updateMap.put("sellerImageUrl", "");
        }else {
            String join = StringUtils.join(list.toArray(), ",");
            updateMap.put("sellerImageUrl", join);
        }
        this.baseMapper.updateByMap(updateMap, sellerId);

        updateMap.put("disabled", DeleteEnum.DELETE.toInt());
        otherAccessoryService.updateByMap(updateMap, id.toString());

        // 刷新微服务端缓存
        UpdateMerchantCacheEvent event = UpdateMerchantCacheEvent.builder().source(this).merchantId(Long.valueOf(sellerId)).build();
        EventBusPusher.syncPost(event);

        return R.ok();
    }

    @Override
    public Integer selectPopSellerInfo(Integer sellerId) {
        return this.baseMapper.selectPopSellerInfo(sellerId);
    }

    @Override
    @Transactional
    public R freeze(Integer sellerId) {
        //查询商户是否有活动订单或余额未提款
        List<Map<String, Object>> checkFreezeList = this.baseMapper.checkFreeze(sellerId);
        if (checkFreezeList.size() > 0) {
            return R.error("该商户有活动订单或未提现暂时不能冻结!");
        }
        PopSysUserEntity popSysUserEntity = popSysUserService.selectOne(new EntityWrapper<PopSysUserEntity>().eq("seller_id", sellerId));
        if (popSysUserEntity == null) {
            return R.error("pop_sys_user表未找到该商户!");
        }
        //状态0：禁用 1：正常
        popSysUserEntity.setStatus(0);
        popSysUserService.updateById(popSysUserEntity);

        SellerInfoEntity sellerInfoEntity = this.baseMapper.selectById(sellerId);
        //失效(0：不失效 1：失效)
        sellerInfoEntity.setDisabled(1);
        this.baseMapper.updateById(sellerInfoEntity);

        UserLoginCensusEntity userLoginCensusEntity = userLoginCensusService.selectById(popSysUserEntity.getMallUserId());
        if (userLoginCensusEntity != null) {
            //是否封号
            userLoginCensusEntity.setDisabled(true);
            userLoginCensusService.updateById(userLoginCensusEntity);
        }
        //冻结商户的商品
        goodsService.frozenGoods(Long.valueOf(sellerId),UserUtils.getCurentUser().getUsername());
        return R.ok();
    }

    @Override
    @Transactional
    public R unfreeze(Integer sellerId) {
        PopSysUserEntity popSysUserEntity = popSysUserService.selectOne(new EntityWrapper<PopSysUserEntity>().eq("seller_id", sellerId));
        //状态0：禁用 1：正常
        popSysUserEntity.setStatus(1);
        popSysUserService.updateById(popSysUserEntity);

        SellerInfoEntity sellerInfoEntity = this.baseMapper.selectById(sellerId);
        //失效(0：不失效 1：失效)
        sellerInfoEntity.setDisabled(0);
        this.baseMapper.updateById(sellerInfoEntity);

        UserLoginCensusEntity userLoginCensusEntity = userLoginCensusService.selectById(popSysUserEntity.getMallUserId());
        if (userLoginCensusEntity != null) {
            //是否封号
            userLoginCensusEntity.setDisabled(false);
            userLoginCensusService.updateById(userLoginCensusEntity);
        }
        //解冻商户的商品
        goodsService.unfreezeGoods(Long.valueOf(sellerId),UserUtils.getCurentUser().getUsername());
        return R.ok();
    }

    @Override
    public R updatePickUp(Integer sellerId, Integer pickUp) {
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("pickUp", pickUp);
        this.baseMapper.updateByMap(updateMap, sellerId);

        // 刷新微服务端缓存
        UpdateMerchantCacheEvent event = UpdateMerchantCacheEvent.builder().source(this).merchantId(Long.valueOf(sellerId)).build();
        EventBusPusher.syncPost(event);

        return R.ok();
    }

    @Override
    public R sellerCopyGoods(Integer sellerId) {
        JSONObject param = new JSONObject();
        param.put("sellerId", sellerId);
        param.put("fromSellerId", 1l);
        String result = HttpClientUtil.doPostJson(sellerCopyGoodsApi, param.toString());
        if (StringUtils.isBlank(result)){
            return R.error("调用接口服务失败！");
        }
        R resultMap = JsonUtils.getJsonToObject(result, R.class);
        int code = (int) resultMap.get("code");
        if (code != 0){
            String message = (String) resultMap.get("msg");
            return R.error(message);
        }
        return R.ok();
    }

    /**
     * 查询需同步订单到erp_order 的商户
     * @return
     */
    @Override
    public List<SellerInfoEntity> selectThirdOrderSyn() {
        return baseMapper.selectThirdOrderSyn();
    }

    @Override
    public R sellerCopyGoodsBatch(Integer[] sellerIds) {
        long start = System.currentTimeMillis();
        log.info("seller copy goods start");
        StringBuilder sb = new StringBuilder();
        JSONObject param = new JSONObject();
        param.put("fromSellerId", 1L);
        for (Integer sellerId : sellerIds){
            param.put("sellerId", Long.valueOf(sellerId));
            String errorMsg = null;
            try {
                String result = HttpClientUtil.doPostJson(sellerCopyGoodsApi, param.toString());
                R r = JsonUtils.getJsonToObject(result, R.class);
                int code = (int) r.get("code");
                if (code != 0){
                    String msg = (String) r.get("msg");
                    errorMsg = msg;
                    log.error("商户 {} 初始化商品失败！msg = {}", sellerId, msg);
                }else {
                    log.info("商户 {} 初始化商品成功！", sellerId);
                }
            }catch (Exception e){
                e.printStackTrace();
                errorMsg = e.getMessage();
                log.error("商户 {} 初始化商品异常！msg = {}", sellerId, e.getMessage());
            }
            if (null != errorMsg){
                sb.append(sellerId + ",");
                SellerCopyGoodsEntity sellerCopyGoods = new SellerCopyGoodsEntity();
                sellerCopyGoods.setSellerId(sellerId.intValue());
                sellerCopyGoods.setResult(errorMsg);
                baseMapper.saveSellerCopyGoodsInfo(sellerCopyGoods);
            }
        }

        long end = System.currentTimeMillis();
        System.out.println("seller copy goods end：" + DateUtils.formatDateTime(end - start));

        if (StringUtils.isNotBlank(sb.toString())){
            return R.error(sb.toString());
        }
        return R.ok();
    }

    @Override
    public synchronized R sellerCopyGoodsBatchAll(Integer nums){
        long start = System.currentTimeMillis();
        List<Long> sellerIds = baseMapper.getNotCopyGoodsSellerIds(nums);
        int size = sellerIds.size();
        log.info("seller copy goods start seller id num：" + size);
        JSONObject param = new JSONObject();
        param.put("fromSellerId", 1L);
        int failNum = 0;
        for (int i = 0; i < size; i++) {
            String errorMsg = null;
            long beginTime = System.currentTimeMillis();
            Long sellerId = sellerIds.get(i);
            log.info("==============sellerId {}   i {}==============", sellerId, i);
            param.put("sellerId", sellerId);
            try {
                String result = HttpClientUtil.doPostJson(sellerCopyGoodsApi, param.toString());
                R r = JsonUtils.getJsonToObject(result, R.class);
                int code = (int) r.get("code");
                if (code != 0){
                    String msg = (String) r.get("msg");
                    errorMsg = msg;
                    log.error("商户 {} 初始化商品失败！msg = {} 剩余 = {}", sellerId, msg, (size - (i+1)));
                }else {
                    log.info("商户 {} 初始化商品成功！剩余 = {}", sellerId, (size - (i+1)));
                }
            }catch (Exception e){
                e.printStackTrace();
                errorMsg = e.getMessage();
                log.error("商户 {} 初始化商品异常！msg = {} 剩余 = {}", sellerId, e.getMessage(), (size - (i+1)));
            }

            if (null != errorMsg){
                failNum += 1;
                SellerCopyGoodsEntity sellerCopyGoods = new SellerCopyGoodsEntity();
                sellerCopyGoods.setSellerId(sellerId.intValue());
                sellerCopyGoods.setResult(errorMsg);
                baseMapper.saveSellerCopyGoodsInfo(sellerCopyGoods);
            }

            long endTime = System.currentTimeMillis();
            log.info("商户： {}  计时结束：{}  耗时：{}", sellerId, new SimpleDateFormat("HH:mm:ss.SSS").format(endTime), DateUtils.formatDateTime(endTime - beginTime));

            try {
                log.info("==============sellerId {}  休眠 0.5s==============", sellerId);
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        long end = System.currentTimeMillis();
        log.info("seller copy goods end time：{} failure num：{}", DateUtils.formatDateTime(end - start), failNum);

        return R.ok();
    }

    //查询省市区的商家
    @Override
    public List<Map<String, Object>> getShops(String area) {
        return this.baseMapper.getShops(area);
    }
}
